package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	//"encoding/json"
	"errors"
)

var (
	host  = "https://sklm-test.vdongzc.com/aliapi"
	token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIiwiYWNjZXNzIjp0cnVlLCJpc3MiOiJhZG1pbiIsImV4cCI6MTY0MDg0NzA3OSwiaWF0IjoxNjQwNzYwNjc5LCJ1c2VybmFtZSI6ImFkbWluIiwiZXh0SW5mbyI6e319.Q_fyaC2q88S8-fo4dhrLY1m7DxcPBDk_3ljBa7ND8bc"
)

func main() {
	UserLogin()
	//PostJson()
	//Get()

}

type Result struct {
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
	Code    int         `json:"code"`
}

//json与 结构体的转换

func (result *Result) ParseData(data interface{}) {
	if result.Code != 200 {
		panic(result.Message)
		return
	}
	if result.Data == nil {
		panic(errors.New("data不存在"))
		return
	}
	jsonData, err := json.Marshal(result.Data)
	if err != nil {
		panic(err)
		return
	}
	err = json.Unmarshal(jsonData, &data)
	if err != nil {
		s := err.Error()
		panic(s)
	}
	return
}

type TokenData struct {
	Token       Token `json:"token"`
	SubPlatform int   `json:"subPlatform"`
}

type Token struct {
	UserId       int64  `json:"userId"`
	AccessToken  string `json:"accessToken"`
	RefreshToken string `json:"refreshToken"`
}
type PageInfo struct {
	EndRow            int     `json:"endRow"`
	HasNextPage       bool    `json:"hasNextPage"`
	HasPreviousPage   bool    `json:"hasPreviousPage"`
	IsFirstPage       bool    `json:"isFirstPage"`
	IsLastPage        bool    `json:"isLastPage"`
	List              []App   `json:"list"`
	NavigateFirstPage int     `json:"navigateFirstPage"`
	NavigateLastPage  int     `json:"navigateLastPage"`
	NavigatePages     int     `json:"navigatePages"`
	NavigatepageNums  []int64 `json:"navigatepageNums"`
	NextPage          int     `json:"nextPage"`
	PageNum           int     `json:"pageNum"`
	PageSize          int     `json:"pageSize"`
	Pages             int     `json:"pages"`
	PrePage           int     `json:"prePage"`
	Size              int     `json:"size"`
	StartRow          int     `json:"startRow"`
	Total             string  `json:"total"`
}
type App struct {
	AppId          string `json:"appId"`
	AppName        string `json:"appName"`
	AppType        int    `json:"appType"`
	CreateTime     string `json:"createTime"`
	Deleted        bool   `json:"deleted"`
	Enable         bool   `json:"enable"`
	Id             string `json:"id"`
	IsThird        bool   `json:"isThird"`
	MerchantName   string `json:"merchantName"`
	MerchantNo     string `json:"merchantNo"`
	MerchantPhone  string `json:"merchantPhone"`
	NotifyUrl      string `json:"notifyUrl"`
	OrderCloseTime int    `json:"orderCloseTime"`
	OwnerId        string `json:"ownerId"`
	PayKey         string `json:"payKey"`
	Platform       int    `json:"platform"`
	Secret         string `json:"secret"`
	TemplateId     string `json:"templateId"`
	Token          string `json:"token"`
	UpdateTime     string `json:"updateTime"`
}

//post url-encode
func UserLogin() {
	var userName, password = "admin", "123456"
	var subPlatform = "1"
	values := url.Values{}
	values.Set("username", userName)
	values.Set("password", password)
	values.Set("subPlatform", subPlatform)
	// GET WAY
	//encode := values.Encode()
	//s := host + "/admin/user/login?" + encode
	//resp, err := http.Get(s)
	// POST WAY
	resp, err := http.PostForm(host+"/admin/user/login", values)
	if err != nil {
		fmt.Printf(err.Error())
	}
	body, _ := ioutil.ReadAll(resp.Body)
	if body == nil {
		panic(errors.New("body is nil"))
	}

	var result = new(Result)
	err = json.Unmarshal(body, &result)
	if err != nil {
		fmt.Printf(err.Error())
	}
	var tokenData = new(TokenData)
	result.ParseData(tokenData)
	fmt.Printf("data %s", tokenData.Token.AccessToken)

}

// PostJson
// application/json

func PostJson() {
	var path = "/admin/app/listPage"
	data := make(map[string]interface{})
	data["appType"] = 2
	data["pageNum"] = 1
	data["pageSize"] = 10
	respdata, _ := json.Marshal(data)
	client := &http.Client{}
	request, err := http.NewRequest(http.MethodPost, host+path, bytes.NewReader(respdata))
	if err != nil {
		fmt.Printf(err.Error())
	}
	request.Header.Add("content-type", "application/json")
	request.Header.Add("Authorization", "Bearer "+token)
	resp, err := client.Do(request)
	if err != nil {
		fmt.Printf(err.Error())
	}
	body, _ := ioutil.ReadAll(resp.Body)
	if body == nil {
		panic(errors.New("body is nil"))
	}
	var result = new(Result)
	err = json.Unmarshal(body, &result)
	if err != nil {
		fmt.Printf(err.Error())
	}
	var page = new(PageInfo)
	result.ParseData(page)
	for index, item := range page.List {
		fmt.Printf("data %d  %s \n", index, item)
	}
}

// 带请求头的GET way
func Get() {
	var path = "/admin/qiniu/getToken"
	client := &http.Client{}
	//http.MethodPost http.MethodGet 来切换请求方式
	request, err := http.NewRequest(http.MethodPost, host+path, nil)
	request.Header.Add("Authorization", "Bearer "+token)
	request.Header.Add("content-type", "application/json")
	resp, err := client.Do(request)
	defer resp.Body.Close()
	if err != nil {
		fmt.Printf(err.Error())
	}
	body, _ := ioutil.ReadAll(resp.Body)
	var result = new(Result)

	err = json.Unmarshal(body, &result)
	if err != nil {
		fmt.Printf(err.Error())
	}
	data := result.Data
	m := data.(map[string]interface{})
	fmt.Printf("appInfo----> %s | %s", m["domain"], m["token"])
}
